#!/usr/bin/env python3
"""
修复球队成员数据
为所有已加入球队但缺少 TeamMember 记录的用户创建记录
"""
from app.core.database import SessionLocal
from app.models.team import Team, TeamMember
from app.models.user import User
from app.utils.helpers import generate_id

def fix_team_members():
    """修复球队成员数据"""
    db = SessionLocal()
    
    try:
        print("🔧 开始修复球队成员数据...\n")
        
        # 获取所有球队
        teams = db.query(Team).all()
        print(f"📊 找到 {len(teams)} 个球队\n")
        
        fixed_count = 0
        
        for team in teams:
            print(f"🏃 检查球队: {team.name} (ID: {team.id})")
            
            # 获取所有用户
            users = db.query(User).all()
            
            for user in users:
                # 检查用户是否在这个球队中
                if user.team_ids and team.id in user.team_ids:
                    # 检查是否已经有 TeamMember 记录
                    existing = db.query(TeamMember).filter(
                        TeamMember.team_id == team.id,
                        TeamMember.user_id == user.id
                    ).first()
                    
                    if not existing:
                        # 创建缺失的 TeamMember 记录
                        role = "captain" if user.id == team.captain_id else "member"
                        
                        # 准备位置信息
                        import json
                        positions_str = None
                        if hasattr(user, 'positions') and user.positions:
                            if isinstance(user.positions, list):
                                positions_str = json.dumps(user.positions)
                            elif isinstance(user.positions, str):
                                positions_str = user.positions
                        
                        team_member = TeamMember(
                            id=generate_id(),
                            team_id=team.id,
                            user_id=user.id,
                            user_name=user.nick_name or "未知用户",
                            avatar=user.avatar if hasattr(user, 'avatar') else None,
                            positions=positions_str,
                            role=role
                        )
                        db.add(team_member)
                        print(f"  ✅ 为用户 {user.nick_name} (ID: {user.id}) 创建 TeamMember 记录 (角色: {role})")
                        fixed_count += 1
                    else:
                        print(f"  ⏭️  用户 {user.nick_name} 已有 TeamMember 记录，跳过")
            
            print()  # 空行分隔
        
        # 提交更改
        db.commit()
        
        print(f"\n🎉 数据修复完成！")
        print(f"📈 总共修复了 {fixed_count} 条记录")
        
    except Exception as e:
        print(f"\n❌ 修复失败: {e}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == "__main__":
    fix_team_members()

